<template>
    <div
        class="fm-uplaod-container"
        :id="uploadId"
    >
        <div
            :id="item.key"
            :style="{width: width+'px', height: height+'px'}"
            :class="{uploading: item.status=='uploading', 'is-success': item.status=='success'}"
            class="upload-file"
            v-for="(item) in fileList"
            :key="item.key">
            <img :src="item.url" >

            <el-progress v-if="item.status=='uploading'" :width="miniWidth*0.9" class="upload-progress" type="circle" :percentage="item.percent"/>

            <label class="item-status" v-if="item.status=='success'">
                <i class="el-icon-upload-success el-icon-check"/>
            </label>

            <div class="uplaod-action">
                <i class="el-icon-view" @click="handlePreviewFile(item.key)" :style="{'font-size': miniWidth/4+'px'}"/>
                <i class="el-icon-delete" @click="handleRemove(item.key)" :style="{'font-size': miniWidth/4+'px'}"/>
            </div>
        </div>

        <div
            class="el-upload el-upload--picture-card"
            v-if="token"
            :style="{width: width+'px', height: height+'px'}"
        >
            <i class="el-icon-plus" :style="{fontSize:miniWidth/4+'px',marginTop: (-miniWidth/8)+'px', marginLeft: (-miniWidth/8)+'px'}"/>
            <input accept="image/*" multiple ref="uploadInput" @change="handleChange" type="file" :style="{width: width+'px', height: height+'px'}" name="file" class="el-upload__input upload-input">
        </div>
    </div>
</template>

<script>
import Viewer from 'viewerjs'
import * as qiniu from 'qiniu-js'
require('viewerjs/dist/viewer.css')

export default {
    props: {
        value: {
            type: Array,
            default: () => []
        },
        width: {
            type: Number,
            default: 100
        },
        height: {
            type: Number,
            default: 100
        },
        token: {
            type: String,
            default: ''
        },
        domain: {
            type: String,
            default: ''
        },
        multiple: {
            type: Boolean,
            default: true
        },
        length: {
            type: Number,
            default: 9
        }
    },
    data() {
        return {
            fileList: this.value.map(item => {
                return {
                    key: item.key ? item.key : (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999),
                    url: item.url,
                    percent: item.percent ? item.percent : 100,
                    status: item.status ? item.status : 'success'
                }
            }),
            viewer: null,
            uploadId: 'upload_' + new Date().getTime()
        }
    },
    computed: {
        miniWidth() {
            if (this.width > this.height) {
                return this.height
            } else {
                return this.width
            }
        }
    },
    watch: {

    },
    methods: {
        handleChange() {
            console.log(this.$refs.uploadInput.files)
            const files = this.$refs.uploadInput.files

            for (let i = 0; i < files.length; i++) {
                const file = files[i]
                const reader = new FileReader()
                const key = (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999)

                reader.readAsDataURL(file)
                reader.onload = () => {
                    this.fileList.push({
                        key,
                        url: reader.result,
                        percent: 0,
                        status: 'uploading'
                    })

                    this.$nextTick(() => {
                        this.uplaodAction2(reader.result, file, key)
                    })
                }
            }

            this.$refs.uploadInput.value = []
        },

        uplaodAction(res, file, key) {
            const changeIndex = this.fileList.findIndex(item => item.key === key)
            console.log(this.fileList.findIndex(item => item.key === key))

            const xhr = new XMLHttpRequest()
            const url = 'http://upload-z2.qiniu.com/putb64/' + file.size
            xhr.open('POST', url, true)
            xhr.setRequestHeader('Content-Type', 'application/octet-stream')
            xhr.setRequestHeader('Authorization', 'UpToken ' + this.token)
            xhr.send(res.split(',')[1])
            xhr.onreadystatechange = () => {
                console.log(xhr)
                if (xhr.readyState === 4) {
                    const resData = JSON.parse(xhr.response)
                    if (resData) {
                        this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
                            ...this.fileList[this.fileList.findIndex(item => item.key === key)],
                            url: this.domain + resData.key,
                            percent: 100
                        })
                        setTimeout(() => {
                            this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
                                ...this.fileList[this.fileList.findIndex(item => item.key === key)],
                                status: 'success'
                            })

                            this.$emit('input', this.fileList)
                        }, 200)
                    } else {
                        this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
                            ...this.fileList[this.fileList.findIndex(item => item.key === key)],
                            status: 'error'
                        })
                        this.fileList.splice(this.fileList.findIndex(item => item.key === key), 1)
                    }
                }
            }
            xhr.onprogress = (res) => {
                console.log('progress', res)
                if (res.total && res.loaded) {
                    this.$set(this.fileList[this.fileList.findIndex(item => item.key === key)], 'percent', res.loaded / res.total * 100)
                }
            }
        },

        uplaodAction2(res, file, key) {
            const _this = this

            const observable = qiniu.upload(file, key, this.token, {
                fname: key,
                mimeType: []
            }, {
                useCdnDomain: true,
                region: qiniu.region.z2
            })

            observable.subscribe({
                next(res) {
                    _this.$set(_this.fileList[_this.fileList.findIndex(item => item.key === key)], 'percent', parseInt(res.total.percent))
                },
                error(err) {
                    console.log(err)
                    _this.$set(_this.fileList, _this.fileList.findIndex(item => item.key === key), {
                        ..._this.fileList[_this.fileList.findIndex(item => item.key === key)],
                        status: 'error'
                    })
                    _this.fileList.splice(_this.fileList.findIndex(item => item.key === key), 1)
                },
                complete(res) {
                    _this.$set(_this.fileList, _this.fileList.findIndex(item => item.key === key), {
                        ..._this.fileList[_this.fileList.findIndex(item => item.key === key)],
                        url: _this.domain + res.key,
                        percent: 100
                    })
                    setTimeout(() => {
                        _this.$set(_this.fileList, _this.fileList.findIndex(item => item.key === key), {
                            ..._this.fileList[_this.fileList.findIndex(item => item.key === key)],
                            status: 'success'
                        })

                        _this.$emit('input', _this.fileList)
                    }, 200)
                }
            })
        },

        handleRemove(key) {
            this.fileList.splice(this.fileList.findIndex(item => item.key === key), 1)
        },

        handlePreviewFile(key) {
            this.viewer && this.viewer.destroy()
            this.uploadId = 'upload_' + new Date().getTime()

            console.log(this.viewer)
            this.$nextTick(() => {
                this.viewer = new Viewer(document.getElementById(this.uploadId))
                this.viewer.view(this.fileList.findIndex(item => item.key === key))
            })
        }
    }
}
</script>
